package com.itfh_wanwan;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

public class A02_wanwan extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String um = req.getParameter("username");
        String pd = req.getParameter("password");
        String pd1 = req.getParameter("password1");
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection rt = DriverManager.getConnection
                    ("jdbc:mysql://127.0.0.1:3306/fh_day03",
                            "root", "123456");
            String name = um;
            String sql = "select * from user where username=?";
            PreparedStatement pst = rt.prepareStatement(sql);
            pst.setString(1,name);
            ResultSet rs = pst.executeQuery();
            String s=null;
           if (rs.next()){
                 s = rs.getString("username");
            }
            if (um.equals(s)){
                resp.setHeader("Refresh","3;URL=registr.jsp");
                resp.getWriter().write("<p style='color:red'>用户已存在3秒后跳转到注册页面</p>");
            }else {
                if (pd.equals(pd1)){
                String sql1 = "insert into user (username,password) values (?,?)";
                PreparedStatement pt = rt.prepareStatement(sql1);
                pt.setString(1,um);
                pt.setString(2,pd1);
                int i = pt.executeUpdate();
                resp.setHeader("Refresh","3;URL=dl.jsp");
                resp.getWriter().write("<p style = 'color:green'>注册成功，3秒后跳入登录页面</p>");
                }else {
                    req.setAttribute("smg","密码不一致请重新输入");
                    req.getRequestDispatcher("registr.jsp").forward(req,resp);
                }

            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
